package cn.zhoujing.security.demo.config;

import cn.zhoujing.security.demo.common.handler.MyAccessAuthorizationManager;
import cn.zhoujing.security.demo.common.handler.MyAccessDeniedHandler;
import cn.zhoujing.security.demo.common.handler.MyAuthenticationEntryPoint;
import cn.zhoujing.security.demo.filter.JwtAuthenticationTokenFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.savedrequest.RequestCacheAwareFilter;
import org.springframework.util.AntPathMatcher;

import static org.springframework.security.config.Customizer.withDefaults;

/**
 * SpringSecurity 配置
 *
 * @author zhoujing
 * @createTime 2024/02/07 - 21:13:00
 */
@Configuration
public class SecurityConfig {

    /**
     * 密码加密类型
     * 用户输入的密码和数据库中的密码使用这个类型进行比较
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * SpringSecurity 过滤链配置
     *
     * @param http
     * @return
     * @throws Exception
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        // 接口认证与鉴权
        http
                .authorizeHttpRequests(authorize -> authorize
                        // 放行指定接口
                        // 放行所有 OPTIONS 请求
                        .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                        // 放行 登录 方法
                        .requestMatchers(HttpMethod.POST, "/user/login").permitAll()
                        // 他请求都需要认证后才能访问，否则返回401
                        .anyRequest()
                        // 动态鉴权
                        .access(myAccessAuthorizationManager()));

        // 接口认证异常处理
        http
                // 异常处理器
                .exceptionHandling(exception -> {
                    // 未认证异常处理器
                    exception.authenticationEntryPoint(new MyAuthenticationEntryPoint());
                    // 权限不足异常处理器
                    exception.accessDeniedHandler(new MyAccessDeniedHandler());
                });

        // 自定义过滤器
        http
                // 将自定义 JwtAuthenticationTokenFilter 过滤器添加至 RequestCacheAwareFilter 前面
                .addFilterBefore(jwtAuthenticationTokenFilter(), RequestCacheAwareFilter.class);

        // 其他配置
        http
                // 禁用默认登录页
                .formLogin(formLogin -> formLogin.disable())
                // 禁用basic明文验证
                .httpBasic(httpBasic -> httpBasic.disable())
                // 禁用默认登出页
                .logout(logout -> logout.disable())
                // 关闭CSRF防御，前后端分离所以用不到
                .csrf(csrf -> csrf.disable())
                // 关闭Session机制，前后端分离所以用不到
                .sessionManagement(management -> management.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 开启跨域
                .cors(withDefaults());

        return http.build();
    }


    /**
     * Spring Security 认证方法
     * <p>
     * 声明它的作用是用它帮我们进行认证操作，调用这个Bean的authenticate方法会由Spring Security自动帮我们做认证。
     *
     * @param authenticationConfiguration
     * @return
     * @throws Exception
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    /**
     * 路径匹配工具
     *
     * @return
     */
    @Bean
    public AntPathMatcher antPathMatcher() {
        return new AntPathMatcher();
    }

    /**
     * 自定义鉴权
     * @return
     */
    @Bean
    public MyAccessAuthorizationManager myAccessAuthorizationManager() {
        return new MyAccessAuthorizationManager();
    }

    /**
     * 自定义JWT解析过滤器
     * @return
     */
    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter();
    }


}
